<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div :class="['Mall4j order-detail page-invoice-detail', $t('language') === 'en'?'order-detail-en':'']">
    <div class="content">
      <div class="crumbs">
        <a
          class="item-a"
          @click="userCenter()"
        >{{ $t('orderDetails.personalCenter') }}</a>
        <span class="arrow">></span>
        <span class="item-span">{{ $t('invoice.InvoiceDetails') }}</span>
      </div>
      <!-- /发票状态 -->
      <div class="info-box">
        <!-- 发票信息 -->
        <div class="invoice-info">
          <div class="item">
            <div class="tit">
              {{ $t('invoice.orderInfo') }}
            </div>
            <div class="con">
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.orderStatus') }}：</span>
                <span class="item-con">{{ [
                  '',
                  $t('obligation'),
                  $t('pendingDelivery'),
                  $t('pendingReceipt'),
                  $t('pendinEvaluation'),
                  $t('completed'),
                  $t('canceled'),
                  $t('grouping'),
                ][orderInfo.status] }}</span>
              </div>
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.orderNumber') }}：</span>
                <span class="item-con">{{ invoiceInfo.orderNumber }}</span>
              </div>
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.orderCreateTime') }}：</span>
                <span class="item-con">
                  {{ orderInfo.createTime }}
                </span>
              </div>
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.invoiceType') }}：</span>
                <span
                  v-if="invoiceInfo.invoiceType === 1"
                  class="item-con"
                >
                  {{ $t('invoice.generalInvoice') }}
                </span>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="tit">
              {{ $t('invoice.invoiceInfo') }}
            </div>
            <div class="con">
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.invoiceStatus') }}：</span>
                <span class="item-con invoice-status">
                  {{ ['',$t('invoice.application'),$t('invoice.invoiced'),$t('invoice.fail')][invoiceInfo.invoiceState] }}
                </span>
              </div>
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.invoiceContent') }}：</span>
                <span
                  v-if="invoiceInfo.invoiceContext === 1"
                  class="item-con"
                >{{ $t('invoice.productDetails') }}</span>
              </div>
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.invoiceTitle') }}：</span>
                <span class="item-con">{{ invoiceInfo.headerName || $t('invoice.personal') }}</span>
              </div>
              <div
                v-if="invoiceInfo.headerType === 1"
                class="con-item"
              >
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.TaxpayerIDNumber') }}：</span>
                <span class="item-con">{{ invoiceInfo.invoiceTaxNumber }}</span>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="tit">
              {{ $t('invoice.invoiceDownload') }}
            </div>
            <div class="con">
              <div
                v-if="invoiceInfo.uploadTime"
                class="con-item"
              >
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.uploadTime') }}：</span>
                <span class="item-con">
                  {{ invoiceInfo.uploadTime || '' }}
                </span>
              </div>
              <div class="con-item">
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.invoiceExchange') }}：</span>
                <span
                  class="item-con invoice-update"
                  @click="showAddOrUpdateDialog(invoiceInfo.orderInvoiceId)"
                >{{ $t('invoice.updateInvoice') }}</span>
              </div>
              <div
                v-if="filePath"
                class="con-item"
              >
                <span
                  class="item-tit"
                  :class="{'invoice-en': $t('language') === 'en' }"
                >{{ $t('invoice.invoiceDownload') }}：</span>
                <el-link
                  v-if="filePath"
                  target="_blank"
                  rel="noopener noreferrer"
                  :href="checkFileUrl(filePath)"
                >
                  <div
                    class="item-con download"
                    :style="{color: textColor}"
                    @mouseenter="HoverDownload"
                    @mouseleave="HoverDownloadSelect"
                  >
                    <img
                      :src="downloadIcon"
                      alt=""
                    >
                    {{ $t('invoice.viewInvoice') }}
                  </div>
                </el-link>
              </div>
            </div>
          </div>
        </div>
        <!-- /发票信息 -->
      </div>
      <!-- 商品信息 -->
      <div class="goods-box">
        <div class="goods-con">
          <div class="shop">
            <span class="name">{{ $t('chat.stores') }}：</span>
            <a
              href="javascript:void(0)"
              class="name"
              @click="toShopPage(orderInfo.shopId)"
            >{{ orderInfo.shopName }}</a>
          </div>
          <div class="order-table">
            <table
              style="border-spacing: 0"
              class="box"
            >
              <tbody>
                <tr class="box-tit">
                  <th>{{ $t('products') }}</th>
                  <th
                    style="width: 145px;"
                    class="tal"
                  >
                    {{ $t('quantity') }}
                  </th>
                  <th style="width: 185px;">
                    {{ $t('priceOne') }}
                  </th>
                  <th style="width: 185px;">
                    {{ $t('totalAll') }}
                  </th>
                </tr>
                <tr
                  v-for="(prod, prodIndex) in orderInfo.orderItemDtos"
                  :key="prodIndex"
                  class="box-tr"
                >
                  <td>
                    <div class="goods-info">
                      <router-link
                        :to="
                          (orderInfo.orderType === 3
                            ? {path:'/detail',query:{prodId:prod.prodId,scoreFee:prod.useScore}}
                            :{path:'/detail',query:{prodId:prod.prodId}} )
                        "
                        target="_blank"
                        class="img"
                      >
                        <img-show :src="prod.pic" />
                      </router-link>
                      <div class="name-sku">
                        <router-link
                          :to="
                            (orderInfo.orderType === 3
                              ? {path:'/detail',query:{prodId:prod.prodId,scoreFee:prod.useScore}}
                              :{path:'/detail',query:{prodId:prod.prodId}} )
                          "
                          target="_blank"
                          class="name"
                        >
                          {{ prod.prodName }}
                        </router-link>
                        <span class="sku">{{ prod.skuName }}</span>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="goods-number">
                      ×{{ prod.prodCount }}
                    </div>
                  </td>
                  <td>
                    <span class="price">￥{{ parsePrice(prod.price)[0] }}.{{
                      parsePrice(prod.price)[1]
                    }}</span>
                  </td>
                  <td>
                    <span class="price">￥{{ parsePrice(prod.productTotalAmount)[0] }}.{{
                      parsePrice(prod.productTotalAmount)[1]
                    }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="goods-total">
            <div class="item">
              <span class="tit">{{
                orderInfo.status === 1 ? $t('orderDetails.amountPayable') : $t('orderDetails.actualAmount')
              }}</span>
              <span class="price big">
                <span v-if="orderInfo.actualTotal">￥{{ parsePrice(orderInfo.actualTotal)[0] }}.{{
                  parsePrice(orderInfo.actualTotal)[1]
                }}</span>
                <span v-if="orderInfo.actualTotal && orderInfo.orderScore">+</span>
                <span v-if="orderInfo.orderScore">{{ orderInfo.orderScore }} {{ $t('orderDetails.points') }}</span>
              </span>
            </div>
          </div>
          <!-- /商品信息 -->
          <!-- 提示弹窗 -->
          <div
            v-if="showTips"
            class="popup-mask"
          />
          <div
            v-if="showTips"
            class="popup-box"
          >
            <div class="tit">
              <div class="text">
                {{ $t('tips') }}
              </div>
              <div
                class="close"
                @click="showTips = 0"
              />
            </div>
            <div class="con">
              <div class="tip">
                <div class="tip-icon warning" />
                <div class="tip-info">
                  <div class="result">
                    {{ $t('orderDetails.confirmCancellation') }}
                  </div>
                  <div class="date">
                    {{ $t('orderDetails.confirmCancellationTips') }}
                  </div>
                  <div class="btns">
                    <a
                      href="javascript:void(0);"
                      class="btn-r"
                      @click="cancelOrder"
                    >{{ $t('determine') }}</a>
                    <a
                      href="javascript:void(0);"
                      class="btn-g"
                      @click="showTips = 0"
                    >{{ $t('cancel') }}</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /商品信息 -->
      <div class="questions-info">
        <div class="title">
          {{ $t('invoice.questions') }}：
        </div>
        <div class="text">
          1、{{ $t('invoice.questions1') }}
        </div>
        <div class="text">
          2、{{ $t('invoice.questions2') }}
        </div>
        <div class="text">
          3、{{ $t('invoice.questions3') }}
        </div>
        <div class="text">
          4、{{ $t('invoice.questions4') }}
        </div>
        <div class="text">
          5、{{ $t('invoice.questions5') }}
        </div>
      </div>
    </div>
    <add-or-edit-invoice
      v-if="showInvoiceAdd"
      ref="invoiceAddOrUpdateRef"
      @toggle-addr-pop="refreshChange"
      @update-data="refreshChange"
      @hide-pop="hidePop"
    />
  </div>
</template>

<script setup>
import invoiceDownloadPng from '@/assets/images/invoice-download.png'
import invoiceDownloadSelectPng from '@/assets/images/invoice-download-select.png'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const orderNumber = ref('')
const orderInvoiceId = ref('')
onMounted(() => {
  orderNumber.value = route.query.orderNumber
  orderInvoiceId.value = route.query.orderInvoiceId

  // 设置网页标题
  document.title = $t('invoice.InvoiceDetails')
  getOrderDetail()
  getInvoiceDetail()
})

// 发票路径
const filePath = ref('')

const textColor = ref('#333333')
const downloadIcon = ref(invoiceDownloadPng)
/**
 * 鼠标移入事件
 */
const HoverDownload = () => {
  textColor.value = '#DF241A'
  downloadIcon.value = invoiceDownloadSelectPng
}

/**
 * 鼠标移出事件
 */
const HoverDownloadSelect = () => {
  textColor.value = '#333333'
  downloadIcon.value = invoiceDownloadPng
}

const showInvoiceAdd = ref(false)
const invoiceAddOrUpdateRef = ref(null)
const invoiceInfo = ref({})
const showAddOrUpdateDialog = (orderInvoiceIdPar) => {
  showInvoiceAdd.value = true
  const param = {
    headerName: invoiceInfo.value.headerName,
    headerType: invoiceInfo.value.headerType,
    invoiceContext: invoiceInfo.value.invoiceContext,
    invoiceState: invoiceInfo.value.invoiceState,
    invoiceTaxNumber: invoiceInfo.value.invoiceTaxNumber,
    invoiceType: invoiceInfo.value.invoiceType
  }
  nextTick(() => {
    invoiceAddOrUpdateRef.value.init(1, param, invoiceInfo.value.orderNumber, invoiceInfo.value.shopId, orderInvoiceIdPar)
  })
}

/**
 * 刷新回调
 */
const refreshChange = (visible) => {
  showInvoiceAdd.value = visible
  getInvoiceDetail()
}

const hidePop = (visible) => {
  showInvoiceAdd.value = visible
}

/**
 * 获取发票详情
 */
const getInvoiceDetail = () => {
  http.get('/p/orderInvoice/info/' + orderInvoiceId.value).then(({ data }) => {
    invoiceInfo.value = data
    getInvoiceFile()
  })
}
const getInvoiceFile = () => {
  if (invoiceInfo.value.fileId) {
    http.get('/p/file/get_file_by_id?fileId=' + invoiceInfo.value.fileId).then(({ data }) => {
      filePath.value = data.filePath
    })
  }
}

const orderInfo = ref({})
let unusedCount = 0
/**
 * 获取订单详情
 */
const getOrderDetail = () => {
  http.get('/p/myOrder/orderDetail', {
    params: {
      orderNumber: route.query.orderNumber
    }
  }).then(({ data }) => {
    orderInfo.value = data
    // 官方自营店判断
    orderInfo.value.shopId = orderInfo.value.shopId || 0
    const virtualInfoList = data.virtualInfoList || []
    // 计算待使用券码总数
    if (virtualInfoList.length) {
      virtualInfoList.forEach(el => {
        if (el.isWriteOff === 0) {
          unusedCount = unusedCount + 1
        }
      })
    }
  })
}

/**
 * 跳转店铺页面
 */
const toShopPage = (shopId) => {
  if (shopId === 0) {
    router.push({ path: '/member-center/integral-mall' })
    return
  }
  router.push({
    path: '/shop-index',
    query: {
      sid: shopId
    }
  })
}

/**
 * 跳转到个人中心
 */
const userCenter = () => {
  router.push({ path: '/user-center' })
}

const showTips = ref(false)
/**
 * 取消订单
 */
const cancelOrder = () => {
  showTips.value = false
  http.put('/p/myOrder/cancel/' + orderNumber.value).then(() => {
    ElMessage({
      type: 'success',
      message: $t('orderDetails.orderCancelled'),
      duration: 1000
    })
    router.push({ path: '/user-center/uc-order' })
  })
}

/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

</script>

<style lang="scss" scoped>
@use "index";
</style>

<style lang="scss" scoped>
@use "../order-detail/index";
</style>

<style lang="scss" scoped>
@use "../user-center/common/scss/user-center";
</style>
